<?php

/**
* AdminAddSlideFormModule.class.php
*
* Concrete page module responsable for creating slide show list
*
* @author     Blazej Zieba <b@zieba.info>
* @copyright  2007 konekto.com
* @version    CVS: $Id:$
*/

require_once("framework/PageModule.class.php");
require_once("HTML/QuickForm.php");
require_once("HTML/QuickForm/Renderer/Default.php");
require_once("ValidationRule.php");
require_once("framework/Yt.class.php");
require_once("framework/Wurfl.class.php");

function onlyOneSet($data)
{

    if(  isSet($data[0]) && $data[1] != '' )
    {
        return false;
    }
    return true;
}  
  
function ytProcessed($id)
{

    $ch = curl_init();
     
    curl_setopt($ch, CURLOPT_URL, "http://www.youtube.com/watch?hl=pl&v=".$id);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_USERAGENT, isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : null );
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0); 
    $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
    curl_setopt($ch, CURLOPT_PROXY,  isset($options['proxy']) ? $options['proxy'] : null ); 
    $data = curl_exec($ch);
    curl_close($ch);
    if ( strpos($data,"Ten film wideo nie został jeszcze przetworzony.") || 
         strpos($data,"Film wideo jest nadal przetwarzany.") || 
         strpos($data,"Żądany film wideo jest niedostępny.") )
    {

        return true;
    }
    
    return false;
}

function ytPublic($id)
{
    try
    {    
        $yt = Yt::getClient();
        $videoEntry = $yt->getVideoEntry($id);
    }
    catch(Zend_Gdata_App_HttpException $e)
    {
        return false;
    }

    return true;
}

function ytHref($data)
{
    if( ytPublic($data) || ytProcessed($data) )
    {
        return true;
    }

    return false;
}

// {{{ SlideShowListModule

class AdminAddSlideFormModule extends PageModule 
{
    
    private $dbh;
    // {{{ Class operations 

    // {{{ SlideShowListModule
    /**
    * C'tor
    */
    
    function AdminAddSlideFormModule()
    {
        trigger_error("ENTER AdminAddSlideFormModule::AdminAddSlideFormModule()", E_USER_NOTICE);
        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        $this->dbh = new PDO($options['dsn_string']);
        $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        
    }
    // }}}
    // {{{ getContent

    /**
    * Function returns page content
    *
    */

    function getContent()
    {
        $defaultValues = array();

        if (isset($_GET['id']))
        {
            $defaultValues = $this->getDefaultValue($_GET['id']);
        }

        trigger_error("ENTER AdminAddSlideFormModule::getContent()", E_USER_NOTICE);
        $form = new HTML_QuickForm("AddSlideForm", 'post', 'index.php?cmd=AdminAddSlide');
        $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');
        $form->setMaxFileSize($global['max_file_size']); 
        $form->addElement('hidden','id', isset($defaultValues['id']) ? $defaultValues['id'] : null);
        $form->addElement('hidden','guide_id', isset($_GET['guide_id']) ? $_GET['guide_id'] : null);
        $form->addElement('text', 'name', _('Nazwa slajdu:'), array('size' => 50, 'maxlength' => 255));
        $form->addElement('textarea', 'desc', _('Opis slajdu:'), array('rows' => 3, 'cols' => 50));

        if ( isset($defaultValues['pic_file']) )
        {
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $form->addElement('static', null,_('Aktualne zdjęcie:'), '<img alt="'.$defaultValues['pic_file'].'" src="'.$global['service_url'].'send_image.php?id='.$defaultValues['pic_file'].'">');
            $form->addElement('checkbox','delete_pic_file', _('Usuń zdjęcie:'));
        }  
        $form->addElement('file', 'pic_file', _('Zdjęcie:'), array());
 
        if ( isset($defaultValues['sound_file']) )
        {
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $form->addElement('static', null,_('Aktulany dźwięk:') ,'<a href="'.$global['service_url'].'send_sound.php?id='.$defaultValues['sound_file'].'">'._('Pobierz dźwięk').'</a>');
            $form->addElement('checkbox','delete_sound_file', _('Usuń dźwięk:'));
        }
        $form->addElement('file', 'sound_file', _('Opis dzwiękowy:'), array());


        if ( isset($defaultValues['video_file']) )
        {
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $yt = Yt::getClient();

            try 
            {
                $videoEntry = $yt->getVideoEntry($defaultValues['video_file']);
 
                if (Wurfl::deviceFactory()->getCapability("model_name") == 'iPhone' || 
                    Wurfl::deviceFactory()->getCapability("is_wireless_device") != 'true')
                {
                    foreach ($videoEntry->mediaGroup->content as $content) {
                        if ( $content->format === '5') {

                            $height =Wurfl::getHeight();
                            $width = Wurfl::getWidth();

                            $form->addElement('static', null, _('Aktulane video:'), '<object width="'.$width.'" height="'.$height.'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ><param name="movie" value="'.$content->url.'"></param><embed src="'.$content->url.'" type="'.$content->format.'" width="'.$width.'" height="'.$height.'" ></embed></object>');

                        }
                    }
                }
                elseif (Wurfl::deviceFactory()->getCapability("streaming_vcodec_mpeg4_sp") >=0)
                {
                    foreach ($videoEntry->mediaGroup->content as $content) {
                        if ( $content->format === '6') {
                            $form->addElement('static', null, _('Aktulane video:'), '<a href="'.$content->url.'">'._('Pobierz video').'</a>');
                        }
                    }
                }
                elseif( Wurfl::deviceFactory()->getCapability("streaming_vcodec_h263_0") >= 0 || 
                        Wurfl::deviceFactory()->getCapability("streaming_vcodec_h263_3") >= 0 )
                {
                    foreach ($videoEntry->mediaGroup->content as $content) {
                        if ( $content->format === '1') {
                            $form->addElement('static', null, _('Aktulane video:'), '<a href="'.$content->url.'">'._('Pobierz video').'</a>');
                        }
                    }

                }
                else
                {
                    $form->addElement('static', null, _('Wideo niedostępne na twoim telefonie.'));
                }
            } 
            catch ( Zend_Exception $e )
            {
                $form->addElement('static', null, _('Wideo w trakcie przetwarzania'));
            } 
  

            $form->addElement('checkbox','delete_video_file', _('Usuń video:'));
        }
        

        $form->addElement('file', 'video_file', _('Wideo :'), array());
        $form->addElement('text', 'yt_id', _('YouTube id:'), array('size' => 11, 'maxlength' => 255));

        $yt_id = $form->getElement('yt_id');
        $yt_id -> setValue($defaultValues['video_file']);

        $form->addElement('text', 'geocode', _('Lokalizacja:'), array('size' => 50, 'maxlength' => 255));

        //Order
        $sth = $this->dbh->prepare("SELECT `order`,name FROM slide WHERE guide_id = :guide_id AND owner = :owner ORDER BY `order` ASC");
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':guide_id', $_GET['guide_id'] ,PDO::PARAM_INT);
        $sth -> execute();
        
        if( isset($defaultValues['id'])  )
        {
            $prefix = _('Zamień z ') ;
        }
        else
        {
            $prefix = _('Dodaj przed ') ;
        }
        
        $rowCount = 0 ;
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) )
        {
            
            $order[ $row['order'] ] = $prefix.$row['name'];
            $rowCount++;
        }

        if( !isset($defaultValues['id'])  )
        {
            $order[ $rowCount ] = _('Dodaj jako ostatni') ;
        }
    
        $select = $form->addElement('select', 'order', _('Kolejność:'), $order );
        $select -> setSelected($rowCount);

        //

        $form->addElement('submit', 'Submit',_('Zapisz'));

        $form->applyFilter('yt_id', 'trim');

        $form->addRule('name', _('Podaj nazwę'), 'required');
        $form->addRule('guide_id', _('Nieprawidłowa wartość trasy'), 'required');
        $form->addRule('id', '', 'NumericOrNull');
        $form->addRule('pic_file',_('Niepoprawny format pliku'),'mymimetype','image/');
        $form->addRule('sound_file',_('Niepoprawny format pliku'),'mymimetype','audio/');
        $form->addRule('video_file',_('Niepoprawny format pliku'),'mymimetype','video/');

        $form->registerRule('onlyoneset', 'callback', 'onlyOneSet');
        $form->addRule(array('video_file','yt_id'),_('Podaj plik lub id'),'onlyoneset');

        $form->registerRule('ythref', 'callback', 'ytHref');
        $form->addRule('yt_id',_('Nieprawidłowy id'),'ythref');

        $form->setDefaults($defaultValues);


        $options = &PEAR::getStaticProperty('CONFIG_INI','TEMPLATES');     
        $statusTpl = new HTML_Template_IT($options["templates_dir"]);
        $statusTpl->loadTemplatefile("status.tpl.xhtml",FALSE,FALSE);
        if ($form->validate()) 
        {
            $data = $form->getSubmitValues(true);
        
            if(isset($data['remove']))
            {
                $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');

                header("Location: ".$global['service_url']."?cmd=AdminRemoveSlide&id=".$data['id']."&guide_id=".$data['guide_id']);            
            }

            if ( $form->getSubmitValue( 'id' ) )
            {
                $this->updateSlide(  $data );
                $statusTpl->setVariable("STATUS",_("Slajd zaktualizowany."));
            }
            else
            {
                
                $this->addSlide(  $data );
                $statusTpl->setVariable("STATUS",_("Slajd dodany."));
               
            }                   
             return $statusTpl->get();

        }
        else
        {
 
            $renderer =& new HTML_QuickForm_Renderer_Default($options);
            $renderer -> setFormTemplate(file_get_contents($options["templates_dir"]."form.tpl.xhtml"));
            $renderer -> setElementTemplate(file_get_contents($options["templates_dir"]."formElement.tpl.xhtml"));
            $renderer -> setRequiredNoteTemplate(file_get_contents($options["templates_dir"]."formRequiredNote.tpl.xhtml"));
            $form -> setRequiredNote(_("* pole obowiązkowe")); 

            if (isset($_GET['id']))
            {
                $form->addElement('submit', 'remove',_('Usuń'));
                $statusTpl->setVariable("STATUS",_("Edycja slajdu"));
            }  
            else
            {
                $statusTpl->setVariable("STATUS",_("Dodaj slajd"));
            } 
            
            $form->accept($renderer);
	        return $statusTpl->get().$renderer->toHtml().$statusTpl->get();
        }

    }
    
    // }}}

    // {{{ addSlide

    /**
    * Function to add slide data 
    *
    */
    private function addSlide($data)
    {

        trigger_error("ENTER AdminAddSlideFormModule::addSlide()", E_USER_NOTICE); 


        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminAddSlideFormModule::addSlide()  Could not begin transaction!", E_USER_ERROR);
        }


        //Change order
        $sth = $this->dbh->prepare("UPDATE slide SET `order` = `order` + 1 WHERE `order` >= :order AND guide_id = :guide_id AND owner = :owner");
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':guide_id',  $data['guide_id'] ,PDO::PARAM_INT);
        $sth -> bindParam(':order', $data['order']  ,PDO::PARAM_INT);
        $sth -> execute();

        //Save data
        $element = array("name","desc","guide_id","geocode","order");
        $tableKey = array();
        $tableValue = array();
        foreach( $data as $key => $value ) 
        {
            if ( in_array($key,$element) )
            {
                $tableKey[] = $this->dbh->quote($key);
                $tableValue[] = $this->dbh->quote($value);
            }
        } 
        $sth = $this->dbh->prepare("INSERT INTO slide (".implode(",",$tableKey).",owner) VALUES (".implode(",",$tableValue).",:owner)") ;
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> execute();
        
        $lastId = $this->dbh->lastInsertId();

        //upload video to You Tube
        if ( $data['yt_id'] != '' )//Yt id was provided
        {
            $sth = $this->dbh->prepare("UPDATE slide SET video_file = :video_file WHERE ROWID = :id AND owner = :owner" ) ;
            $sth -> bindParam(':video_file',  $data['yt_id'] ,PDO::PARAM_STR);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id', $lastId, PDO::PARAM_INT);
            $sth -> execute();
        }
        else
        {    
            $this->saveVideoToYt($lastId, $data['video_file'], $data['name']);
        }
        
        // 

        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');

        $element = array("pic_file","sound_file");
        $tableAssigment = array();

        foreach($data as $key => $value)
        {
            
            if( in_array($key,$element) )
            {
                if ( move_uploaded_file($value["tmp_name"],$options['upload_dir'].$data['guide_id'].$lastId.$value['name']) )
                {
                    $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($data['guide_id'].$lastId.$value['name']);
                }
            }
        }
        
        if ( count ( $tableAssigment ) )
        {
            $sth = $this->dbh->prepare("UPDATE slide SET ".implode(",",$tableAssigment)." WHERE ROWID = :id AND owner = :owner" ) ;
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id', $lastId, PDO::PARAM_INT);
            $sth -> execute();                
        } 


        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminAddSlideFormModule::addSlide()  Could not end transaction !", E_USER_ERROR);
        }


    }

    // }}}

    // {{{ updateSlide
    /**
    * Function to add slide data 
    *
    */
    private function updateSlide($data)
    {

        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminAddSlideFormModule::updateSlide()  Cound not begin transaction !", E_USER_ERROR);
        }

        //Change order
        $sth = $this->dbh->prepare("SELECT `order` FROM slide WHERE rowid = :id AND owner = :owner");
        $sth -> bindParam(':id',$data['id'], PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute();

        $result = $sth->fetch();
        $currentOrder = $result['order'];
        
        $sth = $this->dbh->prepare("UPDATE slide SET `order` = `order` - 1 WHERE `order` > :order AND guide_id = :guide_id AND owner = :owner");
        $sth -> bindParam(':order',$currentOrder, PDO::PARAM_INT);
        $sth -> bindParam(':guide_id',$data['guide_id'], PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute();

        $sth = $this->dbh->prepare("UPDATE slide SET `order` = `order` + 1 WHERE `order` >= :order AND guide_id = :guide_id AND owner =:owner");
        $sth -> bindParam(':order',$data['order'], PDO::PARAM_INT);
        $sth -> bindParam(':guide_id',$data['guide_id'], PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute();
    
        
        //Save data
        $element = array("name","desc","geocode","order");
        $tableAssigment = array();
        foreach( $data as $key => $value ) 
        {
            if ( in_array($key,$element) )
            {
                $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($value);
            }
        } 

        $sth = $this->dbh->prepare("UPDATE slide SET ".implode(",",$tableAssigment)."  WHERE guide_id = :guide_id AND ROWID = :id AND owner = :owner") ;
        $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
        $sth -> bindParam(':guide_id', $data['guide_id'], PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute();

        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
        //Delete uploaded files ?
        if ( isset($data['delete_pic_file']) )
        {

            $sth = $this->dbh->prepare("SELECT pic_file FROM slide WHERE guide_id = :guide_id AND ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> bindParam(':guide_id', $data['guide_id'], PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth->execute( ); 

            $result = $sth->fetch(PDO::FETCH_ASSOC);
            $sth = $this->dbh->prepare("UPDATE slide SET pic_file = null WHERE  guide_id = :guide_id AND ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> bindParam(':guide_id', $data['guide_id'], PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth->execute( );

            if ( !unlink($options['upload_dir'].$result['pic_file']) )
            {
                trigger_error("AdminAddSlideFormModule::updateSlide()  Could not unlink file :".$options['upload_dir'].$result['pic_file'], E_USER_ERROR);
            }
        }

        if ( isset($data['delete_sound_file']) )
        {
            $sth = $this->dbh->prepare("SELECT sound_file FROM slide WHERE  guide_id = :guide_id AND ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> bindParam(':guide_id', $data['guide_id'], PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth->execute( ); 
            $result = $sth->fetch(PDO::FETCH_ASSOC);

            $sth = $this->dbh->prepare("UPDATE slide SET sound_file = null WHERE   guide_id = :guide_id AND ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> bindParam(':guide_id', $data['guide_id'], PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth->execute( ); 

            if ( !unlink($options['upload_dir'].$result['sound_file'])  )
            {
                trigger_error("AdminAddSlideFormModule::updateSlide()  Could not unlink file :".$options['upload_dir'].$result['sound_file'], E_USER_ERROR);
            }
        }
        


        if ( $data['yt_id'] != ''  )
        {
            //yt_id provided 
            $sth = $this->dbh->prepare("UPDATE slide SET video_file = :video_file WHERE ROWID = :id AND owner = :owner" ) ;
            $sth -> bindParam(':video_file',  $data['yt_id'] ,PDO::PARAM_STR);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> execute();
        }


        if ( isset($data['delete_video_file']) || $data['yt_id'] == '')
        {
        
            $this->deleteVideoFromYt( $data['id'] );
            
        }

        $this->updateVideoToYt( $data['id'], $data['video_file'], $data['name']); 

        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');

        $element = array("pic_file","sound_file");
        $tableAssigment = array();

        foreach($data as $key => $value)
        {
            
            if( in_array($key,$element) )
            {
                if ( move_uploaded_file($value["tmp_name"],$options['upload_dir'].$data['guide_id'].$data['id'].$value['name']) )
                {
                    $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($data['guide_id'].$data['id'].$value['name']);
                }
            }
        }
        
        if ( count ( $tableAssigment ) )
        {
            $sth = $this->dbh->prepare("UPDATE slide SET ".implode(",",$tableAssigment)." WHERE  guide_id = :guide_id AND ROWID = :id AND owner = :owner ") ;
            $sth -> bindParam(':id', $data['id'], PDO::PARAM_INT);
            $sth -> bindParam(':guide_id', $data['guide_id'], PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth->execute( ); 
        } 


        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminAddSlideFormModule::updateSlide()  Could not end transaction !", E_USER_ERROR);
        }

    }

    // }}}

    // {{{ getDefaultValues

    /**
    * Function gets default values 
    *
    */
    private function getDefaultValue($id)
    {
        trigger_error("ENTER AdminAddSlideFormModule::getDefaultValues()", E_USER_NOTICE);
        $sth = $this->dbh->prepare("SELECT rowid AS id,* FROM slide WHERE rowid = :id AND owner = :owner ");
        $sth -> bindParam(':id',$id);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> execute();   
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        return $result;
    }
    // }}}


    // {{{ saveVideoToYt

    /**
    * Save video to YouTube
    *
    */
    function saveVideoToYt($lastId, $uploadedVideo, $title)    
    {
        if( !is_uploaded_file($uploadedVideo['tmp_name']) ) 
        { 
            return; 
        }
        $yt = Yt::getClient();
        Zend_Loader::loadClass('Zend_Gdata_YouTube');
        $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
        // create a new VideoEntry object
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

        $myVideoEntry->setVideoTitle($title);
        $myVideoEntry->setVideoDescription($title);
        $myVideoEntry->setVideoCategory('People');
        $myVideoEntry->SetVideoTags($global['service_url']);


        $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
        $tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
        $tokenValue = $tokenArray['token'];
        $postUrl = $tokenArray['url'];

        // place to redirect user after upload
        $nextUrl = $global['service_url'];

        $ch = curl_init();
         
        curl_setopt($ch, CURLOPT_URL, $postUrl .'?nexturl='. $nextUrl);
        curl_setopt($ch, CURLOPT_HEADER,1);
        curl_setopt($ch, CURLOPT_USERAGENT, isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : null );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);//do not follow location
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);//no tunnel
        $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL'); 
        curl_setopt($ch, CURLOPT_PROXY,  isset($global['proxy']) ? $global['proxy'] : null ); 
        curl_setopt($ch, CURLOPT_POST, true);
        $post = array(
            "file"=>"@".$uploadedVideo['tmp_name'],
            "token"=>$tokenValue,
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

        $data = curl_exec($ch);
        curl_close($ch);
        //wait a while to avoid google too many calls error
        sleep(1);

        if ( strpos($data, '?status=200' ) === false )
        {
            preg_match('/status=(...)/',$data,$matches);
            trigger_error("AdminAddSlideFormModule::saveVideoToYt()  Video upload failed. Code : ".$data, E_USER_ERROR);
        }

        //Finally save data to db
        $sth = $this->dbh->prepare("UPDATE slide SET video_file = :video_file WHERE ROWID = :id AND owner = :owner" ) ;
        preg_match('/\&id=(.*)\r\n/',$data,$matches);
        $sth -> bindParam(':video_file',  $matches[1]);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id', $lastId, PDO::PARAM_INT);
        $sth -> execute();  
    }
    // }}}

    // {{{ updateVideoToYt

    /**
    * Update video to YouTube
    *
    */
    function updateVideoToYt( $id, $uploadedVideo, $title)
    {

        if( !is_uploaded_file($uploadedVideo['tmp_name']) ) 
        { 
            return; 
        }

        $sth = $this->dbh->prepare("SELECT video_file FROM slide WHERE ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);
    
        if ( $result['video_file'] != '' )
        {
            $this->deleteVideoFromYt($id);
        }

        $this->saveVideoToYt( $id, $uploadedVideo, $title );
    }
 
    // }}}

    // {{{ deleteVideoFromYt

    /**
    * Delete video file from You Tube
    *
    */
    function deleteVideoFromYt( $id )
    {
     
        $sth = $this->dbh->prepare("SELECT video_file FROM slide WHERE  ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);

        $sth = $this->dbh->prepare("UPDATE slide SET video_file = null WHERE   ROWID = :id AND owner = :owner") ; 
        $sth -> bindParam(':id', $id, PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth->execute( ); 

        if($result['video_file'] == '')
        {
            return;
        }
        
        
        $yt = Yt::getClient();
        
        try
        {
            $videoEntry = $yt->getVideoEntry($result['video_file'],null,true);
            $yt->delete($videoEntry);
        }
        catch(Zend_Gdata_App_HttpException $e)
        {
            trigger_error("AdminAddSlideFormModule:: deleteVideoFromYt() Could not remove video id =  ".$result['video_file'], E_USER_WARNING );
        }
        

        

    }
 
    // }}}
}
// }}} 

?>
